package ro.prjmanager.web;

import net.sourceforge.stripes.controller.StripesFilter;
import net.sourceforge.stripes.util.StringUtil;
import ro.prjmanager.core.context.PrjManagerWebContextBuilder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;



public class SecurityFilter extends StripesFilter {
    private static Set<String> publicUrls = new HashSet<String>();

    static {
        publicUrls.add("/login/Login.jsp");
        publicUrls.add("/actions/loginout/Login.action");
        

    }

    /** Does nothing. */
    public void init(FilterConfig filterConfig) throws ServletException {super.init(filterConfig); }

    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
         HttpServletResponse response = (HttpServletResponse) servletResponse;
        PrjManagerWebContextBuilder.getBuilder().set(request,null);
        if (request.getSession().getAttribute("user") != null) {
            super.doFilter(servletRequest, servletResponse, filterChain);
        }
        else if ( isPublicResource(request) ) {
             super.doFilter(servletRequest, servletResponse, filterChain);
        }
        else {
            // Redirect the user to the loginout page, noting where they were coming from
            String targetUrl = StringUtil.urlEncode(request.getServletPath());

            response.sendRedirect(
                    request.getContextPath() + "/login/Login.jsp?targetUrl=" + targetUrl);
        }
    }

    /**
     * Method that checks the request to see if it is for a publicly accessible resource
     * @param request - HttpeServletRequest - request object
     * @return - true if the requested resource is public
     */
    protected boolean isPublicResource(HttpServletRequest request) {
        String resource = request.getServletPath();

        return publicUrls.contains(request.getServletPath())
                || (!resource.endsWith(".jsp") && !resource.endsWith(".action"));
    }

    /** Does nothing. */
    public void destroy() { super.destroy();}



}
